package com.yili.oa.utils.aop;

import com.yili.oa.utils.annotate.DataBase;
import com.yili.oa.utils.hodle.DataSourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author lxr
 * @version v0.01
 * @date 2019/7/10 0010
 * @email 200890949@qq.com
 */
@SuppressWarnings("ArgNamesErrorsInspection")
@Aspect
@Component
@Order(-1000)
public class DataBaseAspect {

/*    @Around(value = "@annotation(dataBase)")
    public Object around(ProceedingJoinPoint point,DataBase dataBase) throws Throwable {
        Object obj = point.proceed();
        return obj;
    }*/

    @Pointcut("@within(com.yili.oa.utils.annotate.DataBase)")
    public void dbPointCut() {
        System.out.println(111);
    }

    /**
     * 方法
     * @param point
     */
//    @Before("dbPointCut()")
//    public void beforeSwitchDS(JoinPoint point){
//        //获得当前访问的class
//        Class<?> className = point.getTarget().getClass();
//        //获得访问的方法名
//        String methodName = point.getSignature().getName();
//        //得到方法的参数的类型
//        Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();
//
//        String dataSource = DataSourceContextHolder.DEFAULT_DS;
//        try {
//            // 得到访问的方法对象
//            Method method = className.getMethod(methodName, argClass);
//
//            // 判断是否存在@DateBase注解
//            if (method.isAnnotationPresent(DataBase.class)) {
//                DataBase annotation = method.getAnnotation(DataBase.class);
//                // 取出注解中的数据源名
//                dataSource = annotation.value();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        // 切换数据源
//        DataSourceContextHolder.setDB(dataSource);
//    }

    @Before("dbPointCut()")
    public void beforeSwitchDS(JoinPoint point){
        //获得当前访问的class
        Class<?> className = point.getTarget().getClass();
        String dataSource = DataSourceContextHolder.DEFAULT_DS;
        try {
            // 得到访问的方法对象
            if (className.isAnnotationPresent(DataBase.class)){
                DataBase annotation = className.getAnnotation(DataBase.class);
                // 取出注解中的数据源名
                dataSource = annotation.value();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 切换数据源
        DataSourceContextHolder.setDB(dataSource);
    }

    @After("dbPointCut()")
    public void afterSwitchDS(JoinPoint point){
        DataSourceContextHolder.clearDB();
    }
}
